import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

typedef OnConfirmCallBack = Function(String content, VoidCallback popCallBack);

///带标题和编辑框的通用弹窗
class CommonEditWithTitleDialog extends StatefulWidget {
  ///上一次内容
  final String oldContent;

  ///确认内容回调
  final OnConfirmCallBack onConfrim;

  ///提示语
  final String hintText;

  ///右上角按钮文字
  final String confrimText;

  ///顶部标题
  final String title;

  ///编辑行高
  final int editLine;

  ///开启空判断
  final bool isEnableEmptyJudge;

  ///显示删除按钮
  final bool isShowDelete;

  ///中文字符限制
  final int limitZHChar;

  ///最多字回调
  final ValueChanged<int> limitCallback;

  const CommonEditWithTitleDialog(
      {Key key,
      this.oldContent,
      this.onConfrim,
      this.hintText = "请输入内容",
      this.confrimText = "保存",
      this.title = "编辑",
      this.editLine = 1,
      this.isEnableEmptyJudge = true,
      this.isShowDelete = true,
      this.limitZHChar,
      this.limitCallback})
      : assert(editLine > 0, "编辑框行数不正确"),
        super(key: key);

  @override
  _CommonEditWithTitleDialogState createState() =>
      _CommonEditWithTitleDialogState();

  ///跳转方法
  static Future<dynamic> navigatorPushDialog(BuildContext context,
      {String title,
        String confirmText,
      String oldContent,
      OnConfirmCallBack onConfirm,
      int limitZHChar}) {
    VgToolUtils.removeAllFocus(context);
    return VgDialogUtils.showCommonBottomDialog(
      context: context,
      child: CommonEditWithTitleDialog(
        title: title,
        confrimText: confirmText,
        oldContent: oldContent,
        onConfrim: onConfirm,
        limitZHChar: limitZHChar,
      ),
    );
  }
}

class _CommonEditWithTitleDialogState
    extends BaseState<CommonEditWithTitleDialog> {
  TextEditingController _contentController = new TextEditingController();

  StreamController<bool> _deleteController = StreamController.broadcast();

  StreamController<bool> _commitController = StreamController.broadcast();

  @override
  void initState() {
    super.initState();
    _contentController.text = widget?.oldContent;
    _contentController.selection = TextSelection.fromPosition(TextPosition(
        affinity: TextAffinity.downstream,
        offset: '${widget?.oldContent}'.length));
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _updateStatus(widget?.oldContent);
    });
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets, //边距（必要）
      duration: const Duration(milliseconds: 100), //时常 （必要）
      child: Container(
        // height: 120 + ScreenUtils.getBottomBarH(context),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
            color: ThemeRepository.getInstance().getCardBgColor_21263C()),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              height: 10,
            ),
            Row(
              children: <Widget>[
                Container(
                  width: 15,
                ),
                Text(
                  widget?.title ?? "",
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600,color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
                ),
                Spacer(),
                StreamBuilder<bool>(
                    initialData: false,
                    stream: _commitController?.stream,
                    builder: (context, snapshot) {
                      return CommonFixedHeightConfirmButtonWidget(
                        isAlive: snapshot?.data == true,
                        width: 76,
                        height: 30,
                        unSelectBgColor: ThemeRepository.getInstance()
                            .getTextEditHintColor_3A3F50(),
                        selectedBgColor: ThemeRepository.getInstance()
                            .getPrimaryColor_1890FF(),
                        unSelectTextStyle: TextStyle(
                            color: VgColors.INPUT_BG_COLOR,
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            height: 1.2),
                        selectedTextStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            height: 1.2),
                        text: widget?.confrimText,
                        onTap: () {
                          if (snapshot == null ||
                              snapshot.data == null ||
                              snapshot.data == false) {
                            return;
                          }
                          if (widget?.onConfrim != null) {
                            widget?.onConfrim(_contentController?.text,
                                    () => Navigator.of(context).maybePop());
                          }
                        },
                      );
                      // return StadiumFixedWidthWidget(
                      //   height: 30,
                      //   width: 76,
                      //   backgroundColor: snapshot?.data == true
                      //       ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                      //       : Color(0xFFCFD4DB),
                      //   onClick: () {
                      //     if(snapshot == null || snapshot.data == null || snapshot.data == false){
                      //       return;
                      //     }
                      //     if(widget?.onConfrim != null){
                      //       widget?.onConfrim(_contentController?.text,()=>Navigator.of(context).maybePop());
                      //     }
                      //   },
                      //   child: Text(
                      //     widget?.confrimText ?? "",
                      //     style: TextStyle(color: Colors.white, fontSize: 14),
                      //   ),
                      // );
                    }),
                Container(
                  width: 15,
                )
              ],
            ),
            Container(
              height: 10,
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 15),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  color:
                      ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
                  padding: const EdgeInsets.only(left: 15),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: VgTextField(
                          controller: _contentController,
                          maxLines: widget?.editLine ?? 1,
                          minLines: widget?.editLine ?? 1,
                          autofocus: true,
                          limitCallback: widget?.limitCallback,
                          maxLimitLength: widget?.limitZHChar,
                          cursorColor: ThemeRepository.getInstance()
                              .getPrimaryColor_1890FF(),
                          textAlign: TextAlign.start,
                          keyboardAppearance: Brightness.light,
                          decoration: InputDecoration(
                              border: InputBorder.none,
                              counterText: "",
                              hintText: widget?.hintText ?? "",
                              hintStyle: TextStyle(
                                  color: ThemeRepository.getInstance()
                                      .getTextEditHintColor_3A3F50(),
                                  fontSize: 14.0)),
                          style: TextStyle(
                              fontSize: 14,
                              color: ThemeRepository.getInstance()
                                  .getTextMainColor_D0E0F7()),
                          maxLengthEnforced: true,
                          onChanged: (text) {
                            _updateStatus(text);
                          },
                        ),
                      ),
                      Offstage(
                        offstage: !(widget?.isShowDelete ?? true),
                        child: StreamBuilder<bool>(
                            initialData: StringUtils.isNotEmpty(
                                _contentController?.text),
                            stream: _deleteController?.stream,
                            builder: (context, snapshot) {
                              return Offstage(
                                offstage: !(snapshot?.data ?? false),
                                child: GestureDetector(
                                  behavior: HitTestBehavior.translucent,
                                  onTap: () {
                                    _contentController.text = "";
                                    _updateStatus("");
                                  },
                                  child: Padding(
                                    padding: const EdgeInsets.only(
                                        left: 8, right: 8, top: 3, bottom: 3),
                                    child: Container(
                                      width: 17,
                                      height: 17,
                                      decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.white.withOpacity(0.1)),
                                      child: Icon(
                                        Icons.close,
                                        size: 11,
                                        color: ThemeRepository.getInstance()
                                            .getTextMainColor_D0E0F7()
                                            .withOpacity(0.8),
                                      ),
                                    ),
                                  ),
                                ),
                              );
                            }),
                      )
                    ],
                  ),
                ),
              ),
            ),
            // Spacer()
            SizedBox(
              height: 20 + ScreenUtils.getBottomBarH(context),
            )
          ],
        ),
      ),
    );
  }

  void _updateStatus(String text) {
    // if (widget?.oldContent == null|| StringUtils.isEmpty(text)
    //     || widget?.oldContent == text) {
    //   _commitController?.add(false);
    // } else {
    //   _commitController?.add(true);
    // }
    if (StringUtils.isEmpty(text)) {
      _deleteController?.add(false);
    } else {
      _deleteController?.add(true);
    }
    if (StringUtils.isEmpty(text?.trim()) &&
        widget?.isEnableEmptyJudge == true) {
      _commitController?.add(false);
    } else {
      _commitController?.add(true);
    }
  }

  @override
  void dispose() {
    _deleteController.close();
    _commitController.close();
    super.dispose();
  }
}
